<template>
	<view class="conntent">
		<view class="conntent-top" >
			<view class="title">
				宠物身份证
			</view>
			<view class="contents">
				蚂蚁宠物鼻纹识别技术
			</view>
			<view class="info" v-if="type==2">
				<view class="info-icon" v-if="qrCode" @click="showqrCodefun">
					<image :src="httpUrlFn(qrCode)" ></image>
				</view>
				<view class="info-head">
					<image :src="httpUrlFn(head)" ></image>
				</view>
				<view class="info-content">
					<view>{{name}}</view>
					<view>电子证号：{{idcardNo}}</view>
					<view>免疫证明：{{immunityNo}}</view>
				</view>
			</view>
		</view>
		<view class="petinfo">
			<view class="petinfo-title">
				请完善宠物信息
			</view>
			
			<view class="pet-view">
				
				
				
				
				<u--form
								labelPosition="left"
								:model="formdatas"
								:rules="rules"
								ref="uForm"
								
						>
						<u-form-item
								label="头像"
								prop="head"
								label-width="60"
								:required="true"
						>
							<u-upload
									:fileList="fileList1"
									@afterRead="afterRead"
									@delete="deletePic"
									name="1"
									multiple
									:maxCount="1"
								></u-upload>
						</u-form-item>
						<u-form-item
								label="昵称"
								prop="name"
								label-width="60"
								:required="true"
								
						>
							<u--input
									v-model="formdatas.name"
									border="none"
									placeholder="请输入昵称"
							></u--input>
						</u-form-item>
							<!-- <u-form-item
									label="生日"
									prop="birth"
									label-width="60"
									:required="true"
									@click="showdate = true; hideKeyboard()"
									ref="item7"
							>
								<u--input
										v-model="formdatas.birth"
										border="none"
										placeholder="请输入生日"
								></u--input>
							</u-form-item> -->
							<u-form-item
									label="生日"
									prop="birth"
									label-width="60"
									:required="true"
									ref="item7"
							>
								<picker mode="date" :value="date" :start="startDate" :end="endDate" @change="bindDateChange">
														<view class="uni-input">{{formdatas.birth?formdatas.birth:"请选择日期"}}</view>
													</picker>
							</u-form-item>
							
							
							
							<u-form-item
												label="性别"
												prop="sex"
												@click="showSex = true; hideKeyboard()"
												ref="item1"
												label-width="60"
												:required="true"
										>
											<u--input
													v-model="formdatas.sexvalue"
													disabled
													disabledColor="#ffffff"
													placeholder="请选择性别"
													border="none"
											></u--input>
								<u-icon
														slot="right"
														name="arrow-right"
												></u-icon>
							</u-form-item>
							<u-form-item
												label="类型"
												prop="type"
												@click="showtype = true; hideKeyboard()"
												ref="item1"
												label-width="60"
												:required="true"
										>
											<u--input
													v-model="formdatas.type"
													disabled
													disabledColor="#ffffff"
													placeholder="请选择类型"
													border="none"
											></u--input>
								<u-icon
														slot="right"
														name="arrow-right"
												></u-icon>
							</u-form-item>
							<u-form-item
												label="绝育情况"
												prop="ligatFlag"
												@click="showjr = true; hideKeyboard()"
												ref="item1"
												:required="true"
												label-width="100"
										>
											<u--input
													v-model="formdatas.ligatFlagvalue"
													disabled
													disabledColor="#ffffff"
													placeholder="请选择绝育情况"
													border="none"
											></u--input>
								<u-icon
														slot="right"
														name="arrow-right"
												></u-icon>
							</u-form-item>
						<!-- 	<u-form-item
									label="绝育情况"
									prop="userInfo.name"
							>
								<u--input
										v-model="model1.userInfo.name"
										border="none"
										placeholder="请输入昵称"
								></u--input>
							</u-form-item> -->
							
							<u-form-item
									label="宠物照片"
									prop="photos"
									label-width="100"
							>
							
								<u-upload
									:fileList="fileList3"
									@afterRead="afterRead"
									@delete="deletePic"
									name="3"
									multiple
									:maxCount="5"
									:previewFullImage="true"
								></u-upload>
								
							</u-form-item>
							</u-form-item>
								<u-form-item
										label="身份证号"
										prop="idcardNo"
										label-width="100"
										:required="true"
								>
									<u--input
											v-model="formdatas.idcardNo"
											border="none"
											placeholder="请输入身份证号"
									></u--input>
								</u-form-item>
								</u-form-item>
									<u-form-item
											label="免疫证明"
											prop="immunityNo"
											label-width="100"
											:required="true"
									>
										<u--input
												v-model="formdatas.immunityNo"
												border="none"
												placeholder="请输入免疫证明"
										></u--input>
									</u-form-item>
							
						</u--form>
						<!-- description="如果选择保密会报错" -->
						<u-action-sheet
										:show="showSex"
										:actions="actions"
										title="请选择性别"
										
										@close="showSex = false"
										@select="sexSelect"
								>
								</u-action-sheet>
						<u-action-sheet
										:show="showjr"
										:actions="actionsjr"
										title="请选择绝育情况"
										
										@close="showjr = false"
										@select="sexSelectone"
								>
								</u-action-sheet>
								<u-action-sheet
												:show="showtype"
												:actions="actionstype"
												title="请选择类型"
												
												@close="showtype = false"
												@select="sexSelecttwo"
										>
										</u-action-sheet>
							
					
					</view>
				
			</view>
			<view class="foods-bt">
				<u-button type="primary" text="确认保存" color="#F55334" size="large" @click="submit"></u-button>
			</view>
			
		</view>
</template>
<script>
  import { BASE_URL_IMAHE,BASE_URL } from "../../../../utils/https";
	import { savePetIdcard,getPetIdcard } from "@/api/pet";
	export default {
	  name: "serviceindex",
	  computed: {
	          startDate() {
	              return this.getDate('start');
	          },
	          endDate() {
	              return this.getDate('end');
	          }
	      },
	  data() {
		  // const currentDate = this.getDate({
		  //             format: true
		  //         })
		  return {
			
			// date: currentDate,
			actionurl: BASE_URL+"/saveFileUploads",
			fileList3: [],
			fileList1: [],
			showSex: false,
			showjr:false,
			showtype:false,
			showdate:false,
			datevalue: Number(new Date()),
			actions: [{value:"1",
							name: '公',
							},
							{
								value:"2",
								name: '母',
							},
							
						],
			actionstype:[
				{
								name: '猫猫',
				},
				{
				
					name: '狗狗',
				},
			],
				actionsjr: [{   value:"1",
								name: '已绝育',
								},
								{
									name: '未绝育',
									value:"0",
								},
								
							],
							model1: {
								userInfo: {
									name: 'uView UI',
									
								},
							},
						rules: {
							'name': {
								type: 'string',
								required: true,
								message: '请填写昵称',
								trigger: ['blur', 'change']
							},
							'head': {
								type: 'string',
								required: true,
								message: '请上传头像',
								trigger: ['blur', 'change']
							},
						},
						radio: '',
						switchVal: false,
						type:1,
						name:"",
						head:"",
						idcardNo:"",
						immunityNo:"",
						qrCode:"",
						formdatas:{
							
							name:"",
							head:"",
							type:"",
							birth:"",
							sex:"",
							sexvalue:"",
							ligatFlag:"",
							ligatFlagvalue:"",
							photos:"",
							idcardNo:"",
							immunityNo:"",
						},
						petIdcardId:''
			
			}	
			
			
		  
	  },
	  onLoad(options) {
		  // console.log(JSON.parse(options.item))
		this.type=options.type
		if(this.type==2){
			this.petIdcardId=options.petIdcardId
		
			this.getPetIdcardfun()
		}
			
		
	  },
	onReady() {
			//onReady 为uni-app支持的生命周期之一
	    	this.$refs.uForm.setRules(this.rules)
	},
			
		methods:{
			 getDate(type) {
			            const date = new Date();
			            let year = date.getFullYear();
			            let month = date.getMonth() + 1;
			            let day = date.getDate();
			
			            if (type === 'start') {
			                year = year - 60;
			            } else if (type === 'end') {
			                year = year;
			            }
			            month = month > 9 ? month : '0' + month;
			            day = day > 9 ? day : '0' + day;
			            return `${year}-${month}-${day}`;
			        },
			bindDateChange: function(e) {
			            this.formdatas.birth = e.detail.value
			        },
			showqrCodefun(){
				// 预览图片
				var that=this
						uni.previewImage({
							urls: [that.httpUrlFn(that.qrCode)],
							longPressActions: {
								itemList: ['发送给朋友', '保存图片', '收藏'],
								success: function(data) {
									console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
								},
								fail: function(err) {
									console.log(err.errMsg);
								}
							}
						});
			},
			async getPetIdcardfun(){
				var res=await getPetIdcard(JSON.stringify({petIdcardId:this.petIdcardId}))
				// head:"",
				
				// fileList3: [],
				// fileList1: [],
				var filearr=res.petIdcard.photos.split(",")
				filearr.forEach((item,index)=>{
					this.fileList3.push({url: this.httpUrlFn( item)})
					})
				this.fileList1.push({url: this.httpUrlFn( res.petIdcard.head)})
				// photos:"",
				if(res.result==0){
					this.formdatas.type=res.petIdcard.type
					this.formdatas.head=res.petIdcard.head
					this.formdatas.name=res.petIdcard.name
					this.formdatas.birth=res.petIdcard.birth
					this.formdatas.sex=res.petIdcard.sex
					this.formdatas.sexvalue=res.petIdcard.sex==1?"公":"母"
					this.formdatas.ligatFlag=res.petIdcard.ligatFlag
					this.formdatas.ligatFlagvalue=res.petIdcard.ligatFlag==0?"已绝育":"未绝育"
					this.formdatas.idcardNo=res.petIdcard.idcardNo
					this.formdatas.immunityNo=res.petIdcard.immunityNo
					this.head=res.petIdcard.head
					this.name=res.petIdcard.name
					this.idcardNo=res.petIdcard.idcardNo
					this.immunityNo=res.petIdcard.immunityNo
					this.qrCode=res.petIdcard.qrCode
					
					
								
				}
			},
			httpUrlFn(item) {
			   return BASE_URL_IMAHE + item;
			},
			sexSelect(e) {
						this.formdatas.sexvalue = e.name
						this.formdatas.sex = e.value
						this.$refs.uForm.validateField('sex')
					},
			sexSelectone(e) {
						this.formdatas.ligatFlagvalue = e.name
						this.formdatas.ligatFlag = e.value
						this.$refs.uForm.validateField('ligatFlag')
					},
			sexSelecttwo(e) {
						this.formdatas.type = e.name
						this.$refs.uForm.validateField('type')
					},
			dateconfirm(e){
				console.log(e)
			},
		  async submit(){
			
			 
				this.fileList1.forEach((item,index)=>{
					if(item.type){
						this.formdatas.head=item.url.fileUrls[0]
					}else{
						this.formdatas.head=item.url.substring(BASE_URL_IMAHE.length)
					}
				})
				var photos=""
				this.fileList3.forEach((item,index)=>{
					if(item.type){
						if(photos){
							photos=photos+","+item.url.fileUrls[0]
						}else{
							photos=item.url.fileUrls[0]
						}
					}else{
						console.log("实打实打算",BASE_URL_IMAHE.length)
						if(photos){
							photos=photos+","+item.url.substring(BASE_URL_IMAHE.length)
						}else{
							photos=item.url.substring(BASE_URL_IMAHE.length)
						}
					}
				})
				this.formdatas.photos=photos
				if(!this.formdatas.name){
					this.$u.toast('请填写昵称')
					return
				}
				if(!this.formdatas.head){
					this.$u.toast('请上传头像')
					return
				}
				if(!this.formdatas.birth){
					this.$u.toast('请填写生日')
					return
				}
				if(!this.formdatas.sex){
					this.$u.toast('请选择性别')
					return
				}
				if(!this.formdatas.type){
					this.$u.toast('请选择类型')
					return
				}
				if(!this.formdatas.ligatFlag){
					this.$u.toast('请选择是否绝育')
					return
				}
				if(!this.formdatas.idcardNo){
					this.$u.toast('请填写身份信息')
					return
				}
				if(!this.formdatas.immunityNo){
					this.$u.toast('请填写疫苗信息')
					return
				}
				 if(this.petIdcardId){
					 this.formdatas.petIdcardId=this.petIdcardId
				 }
				 console.log(this.formdatas)
				 // return
				
				
				this.formdatas.userId=uni.getStorageSync("userId")?uni.getStorageSync("userId"):""
			 var res=await savePetIdcard(JSON.stringify(this.formdatas))
			 console.log(res)
			 if(res.result==0){
				 uni.showToast({
				   title: "宠物添加成功",
				   icon: "success",
				   duration: 2000,
				 });
				 setTimeout(()=>{
					uni.switchTab({
						url:"/pages/user/index"
					}) 
				 },1000)
				
			 }else{
				uni.showToast({
				  title: "添加失败，请重试",
				  icon: "error",
				  duration: 2000,
				}); 
			 }
						
					},
			// 删除图片
						deletePic(event) {
							this[`fileList${event.name}`].splice(event.index, 1)
							console.log("1111",event,event.name)
						},
						// 新增图片
						async afterRead(event) {
							var that=this
							// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
							let lists = [].concat(event.file)
							let fileListLen = this[`fileList${event.name}`].length
							lists.map((item) => {
								this[`fileList${event.name}`].push({
									...item,
									status: 'uploading',
									message: '上传中'
								})
							})
							for (let i = 0; i < lists.length; i++) {
								const result = await this.uploadFilePromise(lists[i].url)
								
								console.log("result",result)
								let item = this[`fileList${event.name}`][fileListLen]
								this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
									status: 'success',
									message: '',
									url: result
								}))
								fileListLen++
								console.log("222",event,event.name,item,"this.fileList3_",that.fileList3,"this.fileList1_",that.fileList1)
							}
						},
						// 新增图片
						async afterRead2(event) {
							// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
							let lists = [].concat(event.file)
							let fileListLen = this[`fileList${event.name}`].length
							lists.map((item) => {
								this[`fileList${event.name}`].push({
									...item,
									status: 'uploading',
									message: '上传中'
								})
							})
							for (let i = 0; i < lists.length; i++) {
								const result = await this.uploadFilePromise(lists[i].url)
								console.log("result",result)
								let item = this[`fileList${event.name}`][fileListLen]
								this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
									status: 'success',
									message: '',
									url: result
								}))
								fileListLen++
							}
						},
						uploadFilePromise(url) {
							var that=this
							return new Promise((resolve, reject) => {
								let a = uni.uploadFile({
									url: that.actionurl, // 仅为示例，非真实的接口地址
									filePath: url,
									name: 'file',
									formData: {
										user: 'test'
									},
									success: (res) => {
										console.log(JSON.parse(res.data),"result222" ,res.data.data)
										setTimeout(() => {
											resolve(JSON.parse(res.data))
										}, 1000)
									}
								});
							})
						},
		}
	}
	  
</script>

<style scoped lang="scss">
	.conntent{
		width: 100%;
		// height: 100vh;
		background-color: #ffffff;
		.conntent-top{
			width: 751rpx;
			height: 669rpx;
			background: linear-gradient(360deg, rgba(255,255,255,0.1) 3%, rgba(250,185,171,0.1) 16%, #F9603D 100%);
			opacity: 1;
			.title{
				font-size: 69rpx;
				color: #232323;
				line-height: 97rpx;
				padding-top: 220rpx;
				margin-left: 55rpx;
			}
			.contents{
				margin-top: 10rpx;
				font-size: 40rpx;
				color: #232323;
				margin-left: 55rpx;
				line-height: 56rpx;
			}
			.info{
				width: 659rpx;
				height: 281rpx;
				background: #F9603D;
				opacity: 1;
				margin: 25rpx auto 0;
				position: relative;
				display: flex;
				border-radius:0 0 50% 50%/16%;
				.info-icon{
					position: absolute;
					top: 32rpx;
					right:23rpx;
					image{
						width: 31rpx;
						height: 31rpx;
					}
					
				}
				.info-head{
					margin-top: 67rpx;
					margin-left: 83rpx;
					image{
						width: 160rpx;
						height: 160rpx;
						border-radius: 50rpx;
					}
				}
				.info-content{
					display: flex;
					flex-direction: column;
					margin-left: 46rpx;
				}
				.info-content view:nth-child(1){
					margin-top: 114rpx;
					font-size: 37rpx;
					color: #FFFFFF;
					line-height: 52rpx;
				}
				.info-content view:nth-child(2){
					margin-top: 12rpx;
					font-size: 28rpx;
					color: #FFFFFF;
					line-height: 39rpx;
				}
				.info-content view:nth-child(3){
					margin-top: 7rpx;
					display: block;
					font-size: 28rpx;
					color: #FFFFFF;
					line-height: 39rpx;
				}
				
			}
			
		}
		.petinfo{
			padding-left: 35rpx;
			padding-right: 35rpx;
			margin-top: 26rpx;
			.petinfo-title{
				font-size: 33rpx;
				color: #2B2B2B;
				line-height: 46rpx;
			}
			.pet-view{
				padding-left: 30rpx;
			}
		}
	}
	.foods-bt{
		width: 462rpx;
		height: 114rpx;
		margin: 48rpx auto 0;
	}
	
	
</style>